<!--
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-05-31 15:14:25
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-08 17:42:58
 * @FilePath: \nien-vue3-admin\src\views\BusinessConfiguration\sellPriceManagement\components\NationalPart.VUE
 * @Description: 重量模板
-->
<template>
  <div class="edit-box">
    <div class="inp-box">
      <div>计费方式</div>
      <el-select v-model="billingType" clearable>
        <el-option
          v-for="dict in dicts[DictDirection.重量模板计费方式]"
          :key="dict.id"
          :value="dict.dictValue"
          :label="dict.dictLabel"
        ></el-option>
      </el-select>
    </div>
    <div class="inp-box">
      <div>计费单重</div>
      <el-input v-model.number="batchWeight" type="text" clearable></el-input>
    </div>
    <div class="inp-box">
      <inp-val-format v-model:formatValue="batchValue" line-match-type="weight" placeholder="请输入分区名称"></inp-val-format>
    </div>
    <div class="btn-box">
      <el-button type="primary" :icon="CirclePlus" @click="batchAdd">批量新增</el-button>
      <el-button type="primary" :icon="EditPen" @click="batchEdit">批量修改</el-button>
    </div>
  </div>
  <div class="btns-box">
    <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增</el-button>
    <el-button
      type="danger"
      :icon="Delete"
      :loading="batchLoading"
      @click="batchDelete"
    >
      批量删除
    </el-button>
    <el-button type="danger" @click="handleCopyCost">复制成本价重量分区</el-button>
    <el-button type="danger" @click="handleCopySelling">复制销售价重量分区</el-button>
  </div>
  <el-table
    v-loading="loading"
    :data="tableData"
    max-height="400px"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" align="center"></el-table-column>
    <el-table-column label="区间名称" prop="name"></el-table-column>
    <el-table-column label="下限重量" prop="lowerWeight"></el-table-column>
    <el-table-column label="上限重量" prop="upperWeight"></el-table-column>
    <el-table-column label="计费方式" prop="billingType"></el-table-column>
    <el-table-column label="计费单重" prop="billingSingleWeight"></el-table-column>
    <el-table-column label="排序" prop="orderBy"></el-table-column>
    <el-table-column label="操作" width="200">
      <template #default="{row, $index}">
        <el-button text type="primary" @click="handleEdit(row)">修改</el-button>
        <el-divider direction="vertical" class="divider-margin" />
        <el-button
          text
          type="primary"
          :loading="!!row.loading"
          @click="handleDelete(row, $index)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 编辑新增弹窗 -->
  <el-dialog v-model="editVisible" title="新增重量模板" width="600px">
    <div class="form-wrapper">
      <el-form
        ref="editFormRef"
        :model="editData"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="区间名称" prop="name">
              <el-input
                v-model="editData.name"
                placeholder="请输入区间名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下限重量" prop="lowerWeight">
              <el-input-number 
                v-model="editData.lowerWeight"
                placeholder="请输入下限重量"
                :step="0.01"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上限重量" prop="upperWeight">
              <el-input-number 
                v-model.number="editData.upperWeight"
                placeholder="请输入上限重量"
                controls-position="right"
                :step="0.01"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费方式" prop="billingType">
              <el-select
                v-model="editData.billingType"
                filterable
                clearable
              >
                <el-option
                  v-for="dict in dicts[DictDirection.重量模板计费方式]" 
                  :key="dict.id"
                  :value="dict.dictValue"
                  :label="dict.dictLabel"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费单重" prop="billingSingleWeight">
              <el-input-number 
                v-model.number="editData.billingSingleWeight"
                placeholder="请输入计费单重"
                :step="0.01"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="orderBy">
              <el-input-number 
                v-model.number="editData.orderBy"
                placeholder="请输入排序"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <el-button type="info" @click="editCancel">取消</el-button>
      <el-button type="primary" @click="editSave">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts" >
import { ref, defineProps, watchEffect, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { EditPen, CirclePlus, Delete } from '@element-plus/icons-vue'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import InpValFormat from './InpValFormat.vue'
import { weightPartitionList,
  weightPartitionRemove, 
  weightPartitionAdd, 
  batchAddOrUpdate,
  weightPartitionAddOrEdit, copyCostPriceWeight, copySellingPriceWeight } from '@/api/BusinessConfig/sellPriceManagement'
import { validateForm, uuid } from '@/utils'

const props = defineProps({
  basicInfo: {
    type: Object,
    default: () => ({}),
  },
})
const dicts = useDicts()
dicts.setDicts(DictDirection.重量模板计费方式)

const loading = ref<boolean>(false)
const tableData = ref([])

// ----------------单个 新增编辑 -start-------
const editVisible = ref<boolean>(false)
const editData = reactive({
  name: '',
  lowerWeight: undefined,
  upperWeight: undefined,
  billingType: undefined,
  billingSingleWeight: undefined,
  orderBy: undefined,
})
const editFormRef = ref()
const rulec = [{ required: true, message: '不能为空', trigger: ['blur', 'change'] }]
const ruleb = [{ required: true, message: '不能为空', trigger: ['blur'] }]
const rules = {
  name: ruleb,
  lowerWeight: rulec,
  upperWeight: rulec,
  billingType: rulec,
  billingSingleWeight: rulec,
}
const handleEdit = (row) => {
  Object.assign(editData, row)
  editVisible.value = true
}

const handleAdd = () => {
  editVisible.value = true
}

const editCancel = () => {
  editVisible.value = false
}
const editSave = () => {
  validateForm(editFormRef.value, () => {
    const params = {
      ...editData,
      billingType: '1',
      salesProductPriceId: props.basicInfo.id,
    }
    weightPartitionAdd(params).then(({ code }) => {
      if (code === 200) {
        ElMessage.success('添加成功！')
        getList()
        editVisible.value = false
      }
    })
  })
}
// ----------------单个 新增编辑 end-----------

const getList = () => {
  if (!props.basicInfo.id) return
  loading.value = true
  weightPartitionList({
    pageSize: 0,
    pageNum: 0,
    salesProductPriceId: props.basicInfo.id,
  }).then(({ code, data }) => {
    if (code === 200) {
      tableData.value = data
    }
  }).finally(() => {
    loading.value = false
  })
}

// ------------- 批量操作
const batchLoading = ref<boolean>()
const batchWeight = ref<number>()
const billingType = ref<string>()
const selectionList = ref([])
const batchValue = ref<any[]>([])

const handleDelete = (row, index) => {
  if (!row.id) {
    tableData.value.splice(index, 1)
  } else {
    ElMessageBox.confirm('该数据在系统内, 是否继续删除?', '警告', {
      type: 'warning',
    }).then(() => {
      row.loading = true
      weightPartitionRemove(row.id).then(({ code }) => {
        if (code === 200) {
          ElMessage.success('删除成功！')
          getList()
        } else {
          ElMessage.error('删除失败！')
        }
      }).finally(() => {
        row.loading = false
      })
    })
  }
}

const checkBatch = () => {
  const errorLine = []
  batchValue.value.forEach((item, index) => {
    if (!item) errorLine.push(index)
  })

  if (errorLine.length) {
    ElMessage.error(`第${ errorLine.join(',') }行的模板有错误，请改正后重试！`)
    return false
  }
  return true
}
const batchAdd = () => {
  if (checkBatch()) {
    const curUuid = uuid()
    tableData.value.unshift(...batchValue.value.map(item => {
      let name, lowerWeight, upperWeight
      if (Array.isArray(item)) {
        name = `${ item[0] }-${ item[1] }`
        lowerWeight = item[0]
        upperWeight = item[1]
      } else {
        name = item
        lowerWeight = 0
        upperWeight = item
      }
      return { 
        name,
        lowerWeight,
        upperWeight,
        billingType: billingType.value,
        billingSingleWeight: batchWeight.value,
        planTypeId: '1',
        salesProductPriceId: props.basicInfo.id,
        uuid: curUuid,
      }
    }))
  }
}
const handleSelectionChange = (list) => {
  selectionList.value = list
}
const batchDelete = async () => {
  let isDelete = true
  if (selectionList.value.some(i => i.id)) {
    isDelete = await ElMessageBox.confirm('选中的数据包含系统数据, 是否继续删除?', '警告', {
      type: 'warning',
    }).then(() => true).catch(() => false)
  }
  if (isDelete) {
    const unSaved = selectionList.value.filter(i => i.uuid).map(i => i.uuid)
    const saved = selectionList.value.filter(i => i.id).map(i => i.id)
      
    if (unSaved.length) {
      tableData.value = tableData.value.filter(i => !unSaved.includes(i.uuid))
    }
    if (saved.length) {
      batchLoading.value = true
      weightPartitionRemove(saved.join(',')).then(({ code }) => {
        if (code === 200) {
          ElMessage.success('删除成功！')
          getList()
        } else {
          ElMessage.error('删除失败！')
        }
      }).finally(() => {
        batchLoading.value = false
      })
    }
  }
}
const batchEdit = () => {
  if (checkBatch()) {
    if (batchValue.value.length > tableData.value.length) {
      // 超出处理
      batchValue.value.length = tableData.value.length
    }

    batchValue.value.forEach((item, index) => {
      let name, lowerWeight, upperWeight
      if (Array.isArray(item)) {
        name = `${ item[0] }-${ item[1] }`
        lowerWeight = item[0]
        upperWeight = item[1]
      } else {
        name = item
        lowerWeight = 0
        upperWeight = item
      }
      Object.assign(tableData.value[index], {
        name,
        lowerWeight,
        upperWeight,
      })
    })
  }
}

const save = () => weightPartitionAddOrEdit(tableData.value).then(({ code }) => {
  if (code === 200) {
    getList()
    ElMessage.success('保存成功！')
  }
})

const handleCopySelling = () => {
  copySellingPriceWeight(props.basicInfo.id).then(({ code, msg }) => {
    if (code === 200) {
      ElMessage.success(msg)
      getList()
    }
  })
}
const handleCopyCost = () => {
  copyCostPriceWeight(props.basicInfo.id).then(({ code, msg }) => {
    if (code === 200) {
      ElMessage.success(msg)
      getList()
    }
  })
}

// 初始化
watchEffect(getList)
defineExpose({
  save,
})
</script>

<style lang="less" scoped>
.edit-box{
    margin-bottom: 16px;
    display: flex;
    align-items: stretch;
    .inp-box{
       &+.inp-box{
         margin-left: 16px
       }
    }
    .btn-box{
      margin-left: 20px;
      display: flex;
      align-items: flex-end;
    }
   .el-textarea{
     
   }
   
}
.form-wrapper{
  padding: 0 12px;
  /deep/.el-selecet{
    width:100%
  }
  /deep/.el-input-number{
    width: 100%;
     .el-input__inner{
       text-align: left;
     }
  }
}
.btns-box{
  margin-bottom: 12px;
}
.divider-margin{
  margin: 0;
}

</style>